﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Phoenix.Exceptions;
using Phoenix.Frames;
using Phoenix.Framework;

namespace Phoenix.ActionResults
{
    public class WindowActionResult : ViewActionResult
    {
        readonly bool modal;

        public WindowActionResult(
            string viewName, 
            ViewModelBase viewModel, 
            ControllerActionContext context, 
            bool modal = false) : 
            base(viewName, viewModel, CreateWindowContext(context))
        {
            this.modal = modal;
        }

        static ControllerActionContext CreateWindowContext(ControllerActionContext context)
        {
            var frameHost = new FrameHost();
            return new ControllerActionContext(
                context.ControllerAction,
                frameHost,
                frameHost,
                context.Host,
                context.RequestState,
                context.Parameters,
                context.Options);
        }

        protected override void RenderView(Control view)
        {
            var window = view as Window;
            if (window == null)
                throw new WindowExpectedException(string.Format("{0} is not a Window", view.GetType().Name));

            ((FrameHost)Context.NavigationFrame).Initialise(window);
            window.Closing += WindowOnClosing;

            if (modal)
                window.ShowDialog();
            else
                window.Show();
        }

        void WindowOnClosing(object sender, CancelEventArgs cancelEventArgs)
        {
            var window = (Window)sender;
            var requestClosingEventArgs = new RequestClosingEventArgs();
            Context.NavigationFrame.CurrentRequestClosing(requestClosingEventArgs);
            if (requestClosingEventArgs.Cancel)
            {
                cancelEventArgs.Cancel = true;
            }
            else
            {
                window.Closing -= WindowOnClosing;
                Context.NavigationFrame.Dispose();
            }
        }
    }
}